# problems/models.py
from django.db import models
from tag.models import Tag  # 从新的应用中导入 Tag 模型

class Problem(models.Model):
    DIFFICULTY_INDEX_MAPPING = {
        "暂无评定": 0,
        "入门": 1,
        "普及-": 2,
        "普及/提高-": 3,
        "普及+/提高": 4,
        "提高+/省选-": 5,
        "省选/NOI-": 6,
        "NOI/NOI+/CTSC": 7,
    }

    problem_number = models.CharField(max_length=10, unique=True,primary_key=True)  # P/B + 数字
    problem_name = models.CharField(max_length=255)
    difficulty = models.CharField(max_length=50)  # 难度，如 入门, 普及-
    difficulty_index = models.IntegerField(null=True, blank=True)  # 难度标号
    tags = models.ManyToManyField(Tag, related_name='problems')  # 多对多关系，表示题目与标签的关联
    submission_count = models.CharField(max_length=20)  # 提交次数 (字符串形式)
    accepted_count = models.CharField(max_length=20)  # 通过次数 (字符串形式)
    acceptance_rate = models.FloatField()  # 通过率 (浮点数)

    def save(self, *args, **kwargs):
        # 设置 difficulty_index
        self.difficulty = self.difficulty.replace("−", "-")

        if self.difficulty in self.DIFFICULTY_INDEX_MAPPING:
            self.difficulty_index = self.DIFFICULTY_INDEX_MAPPING[self.difficulty]
        else:
            self.difficulty_index = None  # 如果难度不匹配，设置为 None

        super().save(*args, **kwargs)

    def add_tag(self, tag):
        """添加标签"""
        if not self.tags.filter(index=tag.index).exists():
            self.tags.add(tag)
            self.save()
            return True
        return False

    def remove_tag(self, tag):
        """移除标签"""
        if self.tags.filter(index=tag.index).exists():
            self.tags.remove(tag)
            self.save()
            return True
        return False
    
    def __str__(self):
        return f"{self.problem_number} - {self.problem_name}"